package com.synergy.stockflow.product.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.synergy.stockflow.model.Result;
import com.synergy.stockflow.product.entity.Material;
import com.synergy.stockflow.product.entity.UnitConversion;
import com.synergy.stockflow.product.entity.UnitConversion;
import com.synergy.stockflow.product.service.UnitConversionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/unitConversion")
public class UnitConversionController {
    @Autowired
    private UnitConversionService unitConversionService;

    @GetMapping("/index")
    public Result<Page<UnitConversion>> page(@RequestParam(name = "current", defaultValue = "1") int current,
                                             @RequestParam(name = "size", defaultValue = "5") int size,
                                             @RequestParam(name = "unitName", defaultValue = "") String unitName,
                                             @RequestParam(name = "unitId", defaultValue = "") String unitId,
                                             @RequestParam(name = "isMainUnit", defaultValue = "0") Integer isMainUnit
    ) {
        QueryWrapper<UnitConversion> query = new QueryWrapper<>();
        if (unitName != null && unitName.length() > 0) {
            query.lambda()
                    .like(UnitConversion::getUnitName, unitName);
        }
        if (unitId != null && unitId.length() > 0) {
            query.lambda()
                    .like(UnitConversion::getUnitId, unitId);
        }
        query.lambda().orderBy(true,false, UnitConversion::getCreateTime);
        Page<UnitConversion> page = new Page<>(current, size);
        page = unitConversionService.page(page, query);
        return Result.success(page);
    }

    @PostMapping("/insert")
    public Result insert(@RequestBody UnitConversion unitConversion) {
        QueryWrapper<UnitConversion> query = new QueryWrapper<>();
        if (unitConversion.getUnitId() != null && unitConversion.getUnitId().length() > 0) {
            query.lambda().eq(UnitConversion::getUnitId, unitConversion.getUnitId());
        }
        Page<UnitConversion> page = new Page<>(1, 10000);
        Page<UnitConversion> page1 = unitConversionService.page(page, query);
        System.out.println(page1);
        if (page1.getRecords() == null || page1.getRecords().size() == 0) {
            try {
                // 基础必填项校验
                if (StringUtils.isEmpty(unitConversion.getUnitId())) {
                    return Result.error(500, "单位编码不能为空");
                }
                if (StringUtils.isEmpty(unitConversion.getUnitName())) {
                    return Result.error(500, "单位名称不能为空");
                }

                // 主单位逻辑校验
                if (unitConversion.getIsMainUnit() == null) {
                    return Result.error(500, "请选择是否为主单位");
                }
                // 非主单位必须填写baseUnitId和转换率
                if (unitConversion.getIsMainUnit() == 0) {
                    if (StringUtils.isEmpty(unitConversion.getBaseUnitId())) {
                        return Result.error(500, "非主单位必须选择主单位");
                    }
                    if (unitConversion.getConversionRate() == null || unitConversion.getConversionRate().compareTo(BigDecimal.ZERO) <= 0) {
                        return Result.error(500, "转换率必须大于0");
                    }
                } else {
                    // 主单位无需关联baseUnitId，转换率默认为1
                    unitConversion.setBaseUnitId(null);
                    if (unitConversion.getIsMainUnit() == 1) {
                        unitConversion.setConversionRate(new BigDecimal("1"));
                    }

                }

                // 设置创建时间（若前端未传递）
                if (unitConversion.getCreateTime() == null) {
                    unitConversion.setCreateTime(new Date());
                }
                if (unitConversion.getUpdateTime() == null) {
                    unitConversion.setUpdateTime(new Date());
                }

                // 保存数据
                boolean success = unitConversionService.save(unitConversion);
                return Result.success(200, "添加成功：" );
            } catch (Exception e) {
                // 捕获唯一键冲突等异常（如unitId重复）
                return Result.error(500, "添加失败：" + e.getMessage());
            }
        }
        return Result.error(500, "单位编码已存在" );

    }
    @PutMapping("/update")
    public Result update(@RequestBody UnitConversion unitConversions) {
        System.out.println(unitConversions);
        unitConversionService.updateById(unitConversions);

        return Result.success(unitConversions);
    }
    @DeleteMapping("/delete")
    public Result delete(@RequestBody List<String> unitIds) {
        unitConversionService.removeBatchByIds(unitIds);
        return Result.success(unitIds);
    }
}
